// Minimal JS helpers for Flowa portal
(function () {
  var iframeModal = document.getElementById('flowa-iframe-modal');
  var iframeElement = document.getElementById('flowa-iframe');
  var iframeTitle = document.getElementById('flowa-iframe-title');
  var iframeClose = document.getElementById('flowa-iframe-close');
  var iframeBackdrop = document.getElementById('flowa-iframe-backdrop');

  function setActiveNav() {
    try {
      var path = (window.location.pathname || '').replace(/\/$/, '');
      var links = document.querySelectorAll('[data-flowa-nav] a');
      links.forEach(function (a) {
        var href = a.getAttribute('href') || '';
        var normalized = href.replace(/\/$/, '');
        if (normalized && path.indexOf(normalized) === 0) {
          a.classList.add('active');
        }
      });
    } catch (e) {
      // no-op
    }
  }

  // (debug helpers removed)

  // simple i18n helper using window.flowaTranslations
  function t(text) {
    try {
      var lang = 'zh';
      try {
        var sel = document.getElementById('flowa-lang-select');
        lang = (sel && sel.value) || (window.frappe && frappe.boot && (frappe.boot.lang || (frappe.boot.user && frappe.boot.user.language))) || 'zh';
      } catch (e) { lang = 'zh'; }
      var dict = window.flowaTranslations || {};
      var entry = dict[text];
      if (!entry) return text;
      if (typeof entry === 'string') return entry;
      var low = String(lang || 'zh').toLowerCase();
      if (low.indexOf('zh') === 0) return entry.zh || entry.en || text;
      return entry.en || text;
    } catch (e) { return text; }
  }

  function getLang() {
    try {
      var sel = document.getElementById('flowa-lang-select');
      var lang = (sel && sel.value) || (window.frappe && frappe.boot && (frappe.boot.lang || (frappe.boot.user && frappe.boot.user.language))) || 'zh';
      return String(lang || 'zh').toLowerCase();
    } catch (e) { return 'zh'; }
  }

  // language-aware icon text. Keep single Chinese characters for zh; use short 2-3 letter abbreviations for en
  function iconLabel(key) {
    var lang = getLang();
    var zh = {
      items: '品',
      warehouse: '仓',
      inventory: '存',
      new: '新',
      shipments: '发',
      receive: '收',
      bill: '票',
      complete: '完',
      hold: '挂',
      closed: '关',
      cancel: '撤',
      review: '审',
      handover: '交',
      exception: '异',
      all: '全'
    };
    var en = {
      items: 'It',       // Items
      warehouse: 'Wh',   // Warehouse
      inventory: 'Iv',   // Inventory
      new: 'New',        // New
      shipments: 'Shp',  // Shipments
      receive: 'Rcv',    // Receive
      bill: 'Bill',      // Bill
      complete: 'Cmp',   // Complete
      hold: 'Hold',      // On Hold
      closed: 'Cls',     // Closed
      cancel: 'Cxl',     // Cancelled
      review: 'Rev',     // Review
      handover: 'Hd',    // Handover
      exception: 'Ex',   // Exceptions
      all: 'All'         // All
    };
    var dict = (lang.indexOf('zh') === 0) ? zh : en;
    return dict[key] || '';
  }

  function openIframeModal(title, url) {
    if (!iframeModal || !iframeElement) {
      window.location.href = url;
      return;
    }
    try {
      iframeTitle && (iframeTitle.textContent = title || '');
      // 恢复最小注入：仅隐藏 ERP 顶栏/左栏，内容满宽
      iframeElement.onload = function () {
        try { injectEmbeddedStyle(iframeElement.contentDocument || iframeElement.contentWindow.document); } catch (e) {}
      };
      iframeElement.src = url;
      iframeModal.hidden = false;
    } catch (error) {
      window.location.href = url;
    }
  }
  // expose helper to open issue from iframe home
  try { window.FLOWA_OPEN_ISSUE = function(title, url){ openIframeModal(title, url); }; } catch (e) {}
  // expose helper to open ERP pages inside main iframe from home srcdoc
  try {
    window.FLOWA_OPEN_APP = function(url){
      var frame = document.getElementById('flowa-nav-content-frame');
      if (!frame) { window.location.href = url; return; }
      frame.removeAttribute('srcdoc');
      frame.onload = function(){
        try { injectEmbeddedStyle(frame.contentDocument || frame.contentWindow.document); } catch (e) {}
      };
      frame.src = (function(u){
        try {
          var parts = String(u).split('#');
          var base = encodeURI(parts[0]);
          var hash = parts[1] ? ('#' + parts[1]) : '';
          return base + hash;
        } catch (e) { return u; }
      })(url);
    };
  } catch (e) {}

  function fetchIssues(limit) {
    limit = limit || 20;
    var fields = encodeURIComponent(JSON.stringify(["name","subject","status","priority","modified","creation"]));
    var filters = encodeURIComponent(JSON.stringify([["status","!=","Closed"]]));
    var url = '/api/resource/Issue?fields=' + fields + '&filters=' + filters + '&order_by=modified%20desc&limit_page_length=' + limit;
    return fetch(url, { method: 'GET' })
      .then(function(r){ return r.json(); })
      .then(function(d){ return (d && (d.data || d.message)) || []; })
      .catch(function(){ return []; });
  }

  function closeIframeModal() {
    if (!iframeModal || !iframeElement || iframeModal.hidden) {
      return;
    }
    iframeModal.hidden = true;
    iframeElement.src = 'about:blank';
  }

  function setupUserMenu() {
    var toggle = document.getElementById('flowa-user-menu-toggle');
    var menu = document.getElementById('flowa-user-menu');
    if (!toggle || !menu) {
      return;
    }

    var dropdownItems = menu.querySelectorAll('.dropdown-item[data-url]');
    dropdownItems.forEach(function (btn) {
      btn.addEventListener('click', function (event) {
        event.preventDefault();
        var url = btn.getAttribute('data-url');
        var title = btn.getAttribute('data-title') || btn.textContent;
        closeMenu();
        openIframeModal(title, url);
      });
    });

    var logoutActions = menu.querySelectorAll('.logout-action');
    logoutActions.forEach(function (btn) {
      btn.addEventListener('click', function () {
        try {
          fetch('/api/method/upsystem.upsystem.api_i18n.logout_to_flowa', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'X-Frappe-CSRF-Token': (window.frappe && frappe.csrf_token) || ''
            }
          }).then(function () {
            window.location.href = '/flowa/login';
          });
        } catch (error) {
          window.location.href = '/flowa/login';
        }
      });
    });

    function closeMenu() {
      if (!menu.hidden) {
        menu.hidden = true;
        toggle.classList.remove('open');
      }
    }

    toggle.addEventListener('click', function (event) {
      event.stopPropagation();
      var willOpen = menu.hidden;
      menu.hidden = !menu.hidden;
      toggle.classList.toggle('open', willOpen);
    });

    document.addEventListener('click', function (event) {
      if (!menu.hidden && !toggle.contains(event.target) && !menu.contains(event.target)) {
        closeMenu();
      }
    });

    document.addEventListener('keydown', function (event) {
      if (event.key === 'Escape') {
        closeMenu();
      }
    });

    // Ensure user chip shows the correct logged-in user instead of Guest
    function updateUserChip(name) {
      try {
        var chip = document.getElementById('flowa-user-menu-toggle');
        if (!chip) return;
        var nameEl = chip.querySelector('.name');
        var avatarEl = chip.querySelector('.avatar');
        var displayName = (name || '').trim();
        if (!displayName && window.frappe && frappe.boot && frappe.boot.user) {
          displayName = (frappe.boot.user.full_name || frappe.boot.user.name || '').trim();
        }
        if (!displayName) return;
        if (nameEl) nameEl.textContent = displayName;
        if (avatarEl) avatarEl.textContent = (displayName[0] || 'U').toUpperCase();
      } catch (e) {}
    }

    // expose for manual refresh calls if needed
    try { window.FLOWA_UPDATE_USER = updateUserChip; } catch (e) {}

    try {
      if (window.frappe && frappe.boot && frappe.boot.user && frappe.boot.user.name && frappe.boot.user.name !== 'Guest') {
        updateUserChip();
      } else {
        fetch('/api/method/frappe.auth.get_logged_user')
          .then(function(r){ return r.json(); })
          .then(function(d){ var u = (d && (d.message || d.result)) || ''; if (u && u !== 'Guest') { updateUserChip(u); } });
      }
    } catch (e) {}
  }

  if (iframeClose) {
    iframeClose.addEventListener('click', closeIframeModal);
  }
  // 点击遮罩不再自动关闭，必须点关闭按钮
  // if (iframeBackdrop) {
  //   iframeBackdrop.addEventListener('click', closeIframeModal);
  // }

  // 注入最小样式：仅隐藏 ERP 顶部个人中心/导航条与左侧栏，保证内容100%铺满
  function injectEmbeddedStyle(doc) {
    if (!doc) return;
    try {
      var style = doc.getElementById('flowa-embedded-style');
      if (!style) {
        style = doc.createElement('style');
        style.id = 'flowa-embedded-style';
        style.textContent = [
          // 隐藏 ERP 顶部整条导航（包含个人中心、搜索、帮助等），防止跳转到其他界面
          'header.navbar, nav.navbar, header.navbar.navbar-expand, header.navbar.navbar-light { display:none !important; height:0 !important; min-height:0 !important; padding:0 !important; margin:0 !important; overflow:hidden !important; }',
          'nav.navbar + div { margin-top:0 !important; }',
          // 顶部高度变量复位，避免列表页标题条遮挡筛选栏
          ':root { --navbar-height: 0px !important; }',
          '.page-head, .page-head-content { top: 0 !important; }',
          // 隐藏左侧栏，主区单列铺满
          '.layout-side-section, .page-sidebar, .desk-sidebar, .sidebar { display:none !important; width:0 !important; max-width:0 !important; }',
          '.layout-main, .layout-main-section, .page-content, .page-container { width:100% !important; max-width:100% !important; }',
          '.layout-main, .layout-main-section-wrapper, .page-container { grid-template-columns: 1fr !important; }',
          // 去掉容器左右 padding/margin，确保 100% 铺满
          '.container, .page-container, .page-content, .layout-main, .layout-main-section, .standard-page { padding-left:0 !important; padding-right:0 !important; margin-left:0 !important; margin-right:0 !important; }',
          '.page-body, .page-body .container, .page-content-wrapper { padding-left:0 !important; padding-right:0 !important; margin-left:0 !important; margin-right:0 !important; }'
        ].join('\n');
        doc.head && doc.head.appendChild(style);
      }
    } catch (e) {}
  }

  function setupLanguageSwitch() {
    var sel = document.getElementById('flowa-lang-select');
    if (!sel) return;
    var curr = 'zh';
    try {
      curr = (window.frappe && frappe.boot && (frappe.boot.lang || (frappe.boot.user && frappe.boot.user.language))) || '';
      curr = (curr || '').toLowerCase();
      if (curr.indexOf('en') === 0) sel.value = 'en';
      else sel.value = 'zh';
    } catch (e) { sel.value = 'zh'; }

    function translateWith(lang, text) {
      try {
        var dict = window.flowaTranslations || {};
        var entry = dict[text];
        if (!entry) return text;
        if (typeof entry === 'string') return entry;
        if (lang && entry[lang]) return entry[lang];
        if (lang && lang.indexOf('zh') === 0) return entry.zh || entry.en || text;
        return entry.en || text;
      } catch (e) { return text; }
    }

    function applyMenuI18n(lang) {
      try {
        var root = document.querySelector('.flowa-nav');
        if (!root) return;
        // Top-level triggers
        var triggers = root.querySelectorAll('.nav-trigger');
        triggers.forEach(function(btn){
          var raw = (btn.getAttribute('data-i18n') || btn.textContent || '').trim();
          if (raw) btn.textContent = translateWith(lang, raw);
        });
        // Links and data-title
        var links = root.querySelectorAll('.nav-link');
        links.forEach(function(a){
          var label = (a.getAttribute('data-i18n') || a.textContent || '').trim();
          if (label) {
            var t = translateWith(lang, label);
            a.textContent = t;
            a.setAttribute('data-title', t);
          }
        });
        // Subtitles in grouped dropdowns
        var subs = root.querySelectorAll('.nav-subtitle');
        subs.forEach(function(el){
          var key = (el.getAttribute('data-i18n') || el.textContent || '').trim();
          if (key) el.textContent = translateWith(lang, key);
        });

        // Right side simple labels (e.g., language label)
        var right = document.querySelector('.flowa-nav-right');
        if (right) {
          var els = right.querySelectorAll('[data-i18n]');
          els.forEach(function(el){
            var key = (el.getAttribute('data-i18n') || el.textContent || '').trim();
            if (key) el.textContent = translateWith(lang, key);
          });
        }
      } catch (e) {}
    }
    // 初始加载时也根据当前语言立即替换菜单文案，避免短暂显示中文
    applyMenuI18n(sel.value || curr || 'zh');
    sel.addEventListener('change', function () {
      var lang = sel.value || 'zh';
      // 先即时更新菜单文案
      applyMenuI18n(lang);
      try {
        if (window.frappe && frappe.call) {
          // 使用我们应用内的接口，写入并刷新会话语言
          frappe.call({
            method: 'upsystem.upsystem.api_i18n.set_user_language',
            args: { language: lang },
            callback: function () { window.location.reload(); },
            error: function () { window.location.reload(); }
          });
          return;
        }
      } catch (e) { window.location.reload(); }
    });
  }

  function applyRoleMenuVisibility() {
    function applyWith(roles) {
      try {
        roles = roles || [];
        var has = function (roleName) { return Array.isArray(roles) && roles.indexOf(roleName) !== -1; };
        var ACCOUNT = 'shopify Role Account';
        var ADMIN = 'shopify Role Admin'; // 普通运营管理角色，不等同于系统管理员
        var STAFF_ADMIN = 'shopify Role Staff admin';
        var MANUFACTURE = 'shopify Role munufacture';

        var nav = document.querySelector('.flowa-nav');
        if (!nav) return;

        // 1) 只有账户角色才能看到“充值对账”（ADMIN 角色本身不能看到）
        if (!has(ACCOUNT)) {
          var recharge = nav.querySelector('.nav-item[data-menu="recharge"]');
          if (recharge) recharge.style.display = 'none';
        }

        // 2) 只有 staff admin 才展示系统设置里的“员工账号管理”（ADMIN 不自动继承）
        if (!has(STAFF_ADMIN)) {
          var settingsMenu = nav.querySelector('.nav-item[data-menu="settings"]');
          if (settingsMenu) {
            var links = settingsMenu.querySelectorAll('a.nav-link');
            links.forEach(function (a) {
              var href = (a.getAttribute('href') || '').toLowerCase();
              // 兼容 /app/list/User/List 与 /app/List/User/List 两种写法
              if (href.indexOf('/app/list/user/list') === 0 || href.indexOf('/app/list%20user/list') === 0) {
                a.style.display = 'none';
              }
            });
          }
        }

        // 3) 只有 munufacture（且没有 Account / Staff Admin / Admin 角色）时，仅展示 入库 的 打包装箱
        var onlyManufacture = has(MANUFACTURE) && !has(ACCOUNT) && !has(STAFF_ADMIN) && !has(ADMIN);
        if (onlyManufacture) {
          var home = nav.querySelector('.nav-link.nav-home');
          if (home) home.style.display = 'none';

          var items = nav.querySelectorAll('.nav-item');
          items.forEach(function (it) {
            var keep = it.getAttribute('data-menu') === 'inbound';
            if (!keep) it.style.display = 'none';
          });

          var inbound = nav.querySelector('.nav-item[data-menu="inbound"]');
          if (inbound) {
            var links = inbound.querySelectorAll('.nav-dropdown .nav-link');
            links.forEach(function (a) {
              var isPacking = a.getAttribute('href') === '/app/packing-information';
              if (!isPacking) a.style.display = 'none';
            });
          }

          // 如果菜单已绑定事件，直接触发默认链接打开
          var defaultLink = nav.querySelector('.nav-item[data-menu="inbound"] a.nav-link[href="/app/packing-information"]');
          if (defaultLink) setTimeout(function(){ defaultLink.click(); }, 0);
        }
      } catch (e) {}
    }

    try {
      var roles = (window.frappe && frappe.boot && frappe.boot.user && frappe.boot.user.roles) || [];
      if (Array.isArray(roles) && roles.length) {
        applyWith(roles);
        return;
      }
      // 从后端获取角色
      fetch('/api/method/upsystem.upsystem.api_i18n.get_user_roles', { method: 'GET' })
        .then(function(r){ return r.json(); })
        .then(function(d){ applyWith((d && (d.message || d.result)) || []); })
        .catch(function(){ applyWith([]); });
    } catch (e) { applyWith([]); }
  }

  function setupNavMenus() {
    var nav = document.querySelector('.flowa-nav');
    if (!nav) {
      return;
    }

    var items = Array.prototype.slice.call(nav.querySelectorAll('.nav-item.has-dropdown'));
    var mainEl = document.querySelector('.flowa-main');
    var content = document.getElementById('flowa-nav-content');
    var frame = document.getElementById('flowa-nav-content-frame');
    var activeLink = null;

    function setActiveLink(link) {
      if (activeLink) {
        activeLink.classList.remove('active');
      }
      if (link) {
        link.classList.add('active');
      }
      activeLink = link || null;
    }
    

    function normalizeUrl(rawUrl) {
      if (!rawUrl) return '';
      // keep hash; encode path/query safely
      var parts = String(rawUrl).split('#');
      var base = encodeURI(parts[0]);
      var hash = parts[1] ? ('#' + parts[1]) : '';
      return base + hash;
    }

    // use shared injector

    function renderHome(link) {
      if (!frame || !content) return;
      content.hidden = false;
      var loading = [
        '<!doctype html>',
        '<html><head><meta charset="utf-8">',
        '<link rel="stylesheet" href="/assets/upsystem/css/flowa.css">',
        '<style>body{padding:18px;background:#fff}</style>',
        '</head><body>',
        '<div class="flowa-dashboard-grid"><div class="flowa-card">'+ t('加载中...') +'</div></div>',
        '</body></html>'
      ].join('');
      frame.removeAttribute('src');
      frame.srcdoc = loading;

      function fetchStats(){
        function doFetch(path){
          var url = path + (path.indexOf('?')>-1?'&':'?') + 't=' + Date.now();
          return fetch(url, { method: 'GET' })
            .then(function(r){ return r.json(); })
            .then(function(d){
              var payload = (d && (d.message || d.result)) || {};
              return payload;
            });
        }
        // Prefer two-level module path first as per deployment convention
        return doFetch('/api/method/upsystem.upsystem.api_stats.get_home_stats')
          .catch(function(){ return doFetch('/api/method/erpnext.upsystem.upsystem.api_stats.get_home_stats'); });
      }

      Promise.all([
        fetchIssues(20),
        fetchStats()
      ]).then(function(results){
        var issues = results[0] || [];
        var stats = results[1] || {};
        function nf(n){ try { return (Number(n)||0).toLocaleString(); } catch(e){ return String(n||0); } }
        function fdt(s){
          try {
            if (!s) return '';
            var d = new Date(s);
            if (isNaN(d)) return String(s);
            function pad(n){ return (n<10?'0':'') + n; }
            return d.getFullYear() + '-' + pad(d.getMonth()+1) + '-' + pad(d.getDate()) + ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes());
          } catch(e){ return String(s||''); }
        }
        var items = (issues || []).map(function(it){
          var name = it.name || '';
          var title = (it.subject || name).replace(/</g,'&lt;');
          var status = it.status || '';
          var pr = it.priority || '';
          var when = fdt(it.creation || it.modified);
          var url = '/app/issue/' + encodeURIComponent(name);
          var safeTitle = (t('问题') + ': ' + (it.subject || name)).replace(/["']/g, '');
          return '<li class="flowa-issue-item" style="padding:8px 0;border-bottom:1px solid #f1f5f9;">'
            + '<a href="#" data-url="' + url + '" data-title="' + safeTitle.replace(/</g,'&lt;') + '"'
            + ' onclick="var u=this.getAttribute(\'data-url\'); var tt=this.getAttribute(\'data-title\'); parent.FLOWA_OPEN_ISSUE(tt,u); return false;"'
            + ' class="flowa-link" style="color:#111827;">' + title + '</a>'
            + '<div class="flowa-muted" style="font-size:12px;margin-top:2px;">' + status + (when?(' · ' + when):'') + (pr?(' · '+pr):'') + '</div>'
            + '</li>';
        }).join('') || '<li class="flowa-issue-item" style="padding:8px 0;">'+ t('暂无需要跟踪的问题') +'</li>';

        // Precomputed filtered URLs for quick navigation
        var dt = new Date();
        function pad(n){ return n<10 ? ('0'+n) : (''+n); }
        var todayStr = dt.getFullYear() + '-' + pad(dt.getMonth()+1) + '-' + pad(dt.getDate());
        function encFilters(arr){ try{ return encodeURIComponent(JSON.stringify(arr)); }catch(e){ return ''; } }
        // 订单区域：按你确认可用的方式，统一采用简单路径跳转（与其它红框链接一致），不附带过滤参数
        // 注意：Doctype 段保持原样（含空格），不要做 encode
        var orderListURL = "/app/List/Sales Order/List";
        var urlPendingReview = orderListURL;
        var urlToDeliver = orderListURL;
        var urlShipped = orderListURL;

        var html = [
          '<!doctype html>',
          '<html><head><meta charset="utf-8">',
          '<link rel="stylesheet" href="/assets/upsystem/css/flowa.css">',
          '<style>body{padding:18px;background:#fff}</style>',
          '</head><body>',
          '<div class="flowa-dashboard-grid">',
          // 顶部左：余额卡
          '  <div class="flowa-balance-card">',
          '    <div class="amount">' + nf(stats.balance) + '</div>',
          '    <div class="flowa-muted" style="color:rgba(255,255,255,0.85);">'+ t('剩余单量') +'</div>',
          '    <div class="flowa-muted" style="color:rgba(255,255,255,0.9);font-size:13px;margin-top:8px;">'
          + t('当天预估物流费') + ': <strong>' + nf(stats.reserved_logistics_today) + '</strong></div>',
          // 查看单量日志 / 查看账户余额：直接在主 iframe 中打开 ERP 内页，避免嵌套 /flowa 造成双导航
          '    <div class="flowa-inline-actions" style="margin-top:12px;">'
          + '      <a class="flowa-chip" href="#" onclick="parent.FLOWA_OPEN_APP(\'/app/List/Acct Balance/List\');return false;">'
          +            t('查看单量日志')
          + '      </a>'
          + '      <a class="flowa-chip" href="#" onclick="parent.FLOWA_OPEN_APP(\'/app/List/Acct Balance/List\');return false;">'
          +            t('查看账户余额')
          + '      </a>'
          + '    </div>',
          '  </div>',
          // 右侧：容器跨两行（与左侧蓝卡+问题跟踪等高）
          '  <div class="flowa-grid" style="grid-column:2;grid-row:1 / span 2;">',
          '    <div class="flowa-card flowa-col-12">',
          '      <div class="flowa-section-title">'+ t('商品') +'</div>',
          '      <div class="flowa-stats-row">',
          '        <a href="#" onclick="parent.FLOWA_OPEN_APP(\'/app/List/Item/List\');return false;" class="flowa-stat" style="text-decoration:none;color:inherit;display:flex;align-items:center;gap:10px;"><div><div class="flowa-muted" style="font-size:12px;">'+ t('SKU总数') +'</div><div><strong>' + nf(stats.item_count) + '</strong></div></div></a>',
          '        <a href="#" onclick="parent.FLOWA_OPEN_APP(\'/app/List/Bin/List\');return false;" class="flowa-stat" style="text-decoration:none;color:inherit;display:flex;align-items:center;gap:10px;"><div><div class="flowa-muted" style="font-size:12px;">'+ t('有库存商品数') +'</div><div><strong>' + nf(stats.have_stock_item_count) + '</strong></div></div></a>',
          '        <a href="#" onclick="parent.FLOWA_OPEN_APP(\'/app/List/Bin/List\');return false;" class="flowa-stat" style="text-decoration:none;color:inherit;display:flex;align-items:center;gap:10px;"><div><div class="flowa-muted" style="font-size:12px;">'+ t('库存总数') +'</div><div><strong>' + nf(stats.total_inventory_qty) + '</strong></div></div></a>',
          '        <div></div>',
          '      </div>',
          '    </div>',
          '    <div class="flowa-card flowa-col-12">',
          '      <div class="flowa-section-title">'+ t('订单') +'</div>',
          '      <div class="flowa-stats-row">',
          '        <a href="#" onclick="parent.FLOWA_OPEN_APP(\'' + urlPendingReview + '\');return false;" class="flowa-stat" style="text-decoration:none;color:inherit;display:flex;align-items:center;gap:10px;"><div><div class="flowa-muted" style="font-size:12px;">'+ t('待审核') +'</div><div><strong>' + nf(stats.orders_pending_review || 0) + '</strong></div></div></a>',
          '        <a href="#" onclick="parent.FLOWA_OPEN_APP(\'' + urlToDeliver + '\');return false;" class="flowa-stat" style="text-decoration:none;color:inherit;display:flex;align-items:center;gap:10px;"><div><div class="flowa-muted" style="font-size:12px;">'+ t('待发货') +'</div><div><strong>' + nf(stats.orders_to_deliver || 0) + '</strong></div></div></a>',
          '        <a href="#" onclick="parent.FLOWA_OPEN_APP(\'' + urlShipped + '\');return false;" class="flowa-stat" style="text-decoration:none;color:inherit;display:flex;align-items:center;gap:10px;"><div><div class="flowa-muted" style="font-size:12px;">'+ t('已发货') +'</div><div><strong>' + nf(stats.orders_shipped || 0) + '</strong></div></div></a>',
          '      </div>',
          '    </div>',
        '    <div class="flowa-card flowa-col-12">',
        '      <div class="flowa-section-title">'+ t('物流') +'</div>',
        '      <div class="flowa-stats-row">',
        '        <a href="#" onclick="parent.FLOWA_OPEN_APP(&#39;/oms_exception&#39;);return false;" class="flowa-stat" style="text-decoration:none;color:inherit;display:flex;align-items:center;gap:10px;"><div><div class="flowa-muted" style="font-size:12px;">'+ t('异常订单') +'</div><div><strong>' + nf(stats.logistics_exception || 0) + '</strong></div></div></a>',
        '        <a href="#" onclick="parent.FLOWA_OPEN_APP(&#39;/oms_tracking?mode=in_transit&#39;);return false;" class="flowa-stat" style="text-decoration:none;color:inherit;display:flex;align-items:center;gap:10px;"><div><div class="flowa-muted" style="font-size:12px;">'+ t('运送中订单') +'</div><div><strong>' + nf(stats.logistics_in_transit || 0) + '</strong></div></div></a>',
        '        <a href="#" onclick="parent.FLOWA_OPEN_APP(&#39;/oms_tracking?mode=delivered&#39;);return false;" class="flowa-stat" style="text-decoration:none;color:inherit;display:flex;align-items:center;gap:10px;"><div><div class="flowa-muted" style="font-size:12px;">'+ t('已送达订单') +'</div><div><strong>' + nf(stats.logistics_delivered || 0) + '</strong></div></div></a>',
        '      </div>',
        '    </div>',
          '  </div>',
          // 左下：问题跟踪（与蓝卡同宽）
          '  <div class="flowa-card" style="max-height:calc(100vh - 280px);overflow:auto;">',
          '    <div class="flowa-section-title">'+ t('问题跟踪') +'</div>',
          '    <ul style="list-style:none;padding:0;margin:0;">' + items + '</ul>',
          '  </div>',
          '</div>',
          '</body></html>'
        ].join('');

        frame.removeAttribute('src');
        frame.srcdoc = html;
        setActiveLink(link);
      });
    }

    function openNavContent(link, url) {
      if (!frame || !content) {
        window.location.href = url;
        return;
      }
      content.hidden = false;
      frame.removeAttribute('srcdoc');
      // 最小注入（隐藏 ERP 顶栏/左栏，保证 100% 铺满）
      frame.onload = function () {
        try { injectEmbeddedStyle(frame.contentDocument || frame.contentWindow.document); } catch (err) {}
      };
      frame.src = normalizeUrl(url);
      setActiveLink(link);
    }

    // hover wiring（同时兼容 pointer 与 mouse 事件，确保悬浮即可点击）
    items.forEach(function (item) {
      var trigger = item.querySelector('.nav-trigger');
      if (!trigger) return;
      // 打开/关闭
      var open = function () { item.classList.add('open'); };
      var close = function () { item.classList.remove('open'); };
      // 兼容性：同时绑定 pointer 与 mouse
      item.addEventListener('pointerenter', open);
      item.addEventListener('pointerleave', close);
      item.addEventListener('mouseenter', open);
      item.addEventListener('mouseleave', close);
      trigger.addEventListener('focus', open);
      trigger.addEventListener('blur', function () {
        setTimeout(function () { if (!item.contains(document.activeElement)) close(); }, 0);
      });
      // 阻止一级触发器默认点击行为，避免需要“先点一次”
      trigger.addEventListener('click', function (e) {
        e.preventDefault();
        open();
      });
      // 键盘 Esc 关闭
      trigger.addEventListener('keydown', function (event) { if (event.key === 'Escape') { close(); trigger.blur(); } });
    });

    var navLinks = nav.querySelectorAll('.nav-link');
    navLinks.forEach(function (link) {
      if (link.dataset && link.dataset.home === '1') {
        link.addEventListener('click', function (event) { event.preventDefault(); renderHome(link); });
        return;
      }
      if (link.classList.contains('pending')) return;
      link.addEventListener('click', function (event) {
        var url = link.getAttribute('href');
        if (!url) return;
        event.preventDefault();
        openNavContent(link, url);
        items.forEach(function (item) { item.classList.remove('open'); var t = item.querySelector('.nav-trigger'); if (t) t.blur(); });
      });
    });

    // initial render
    var defaultLink = null;
    if (window.__flowa_default_link_selector) {
      defaultLink = nav.querySelector(window.__flowa_default_link_selector);
    }
    if (defaultLink) {
      var url = defaultLink.getAttribute('href');
      if (url) openNavContent(defaultLink, url);
    } else {
      var defaultHome = nav.querySelector('.nav-link.nav-home');
      renderHome(defaultHome);
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function () {
      setActiveNav();
      setupUserMenu();
      setupLanguageSwitch();
      applyRoleMenuVisibility();
      setupNavMenus();
    });
  } else {
    setActiveNav();
    setupUserMenu();
    setupLanguageSwitch();
    applyRoleMenuVisibility();
    setupNavMenus();
  }
})();


